package com.example.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.mapper.SysMenuMapper;
import com.example.utils.ShiroUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
public class ShiroController {
    private static Logger LOGGER = LoggerFactory.getLogger(ShiroController.class);
    @Resource
    private SysMenuMapper sysMenuMapper;

    @RequestMapping("/loginindex")
    public String loginindex() {
        //ShiroUtils.logout();
        return "login";
    }

    /**
     * 登录测试
     * http://localhost:7011/userLogin?userName=admin&amp;passWord=admin
     */
    @ResponseBody
    @RequestMapping("/login")
    public JSONObject userLogin(@RequestParam(value = "username") String userName, @RequestParam(value = "password") String passWord) {
        JSONObject jsonObject=new JSONObject();
        try {
            Subject subject = ShiroUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(userName, passWord);

            subject.login(token);
            jsonObject.put("code", 200);
            jsonObject.put("msg", "登录成功");
            LOGGER.info("登录成功");
        } catch (Exception e) {
            e.printStackTrace();
            jsonObject.put("code", 0);
            jsonObject.put("msg", e.getMessage());
        }
        return jsonObject;
    }

    /**
     * 服务器每次重启请求该接口之前必须先请求上面登录接口
     * http://localhost:7011/menu/list 获取所有菜单列表
     * 权限要求：sys:sysuser:shiro
     */
    @ResponseBody
    @RequestMapping("/menu/list")
    @RequiresPermissions("sys:sysuser:shiro")
    public List list() {
        return sysMenuMapper.selectList(null);
    }

    /**
     * 用户没有该权限，无法访问
     * 权限要求：ccc:ddd:bbb
     */
    @RequestMapping("/menu/list2")
    @RequiresPermissions("ccc:ddd:bbb")
    public List list2() {
        return sysMenuMapper.selectList(null);
    }

    /**
     * 退出测试，退出后没有任何权限
     */
    @RequestMapping("/loginout")
    public void logout(HttpServletResponse response) throws IOException {
        ShiroUtils.logout();
        response.sendRedirect("loginindex");
        //return "success";
    }

    /**
     * 退出测试，退出后没有任何权限
     */
    @RequestMapping("/notRole")
    public String notRole() {
        ShiroUtils.logout();
        return "notRole";
    }
}